# -*- coding: utf-8 -*-
from scrapy.exceptions import IgnoreRequest
from scrapy import Request
from zc_core.util.http_util import retry_request
from zc_core.spiders.base import BaseSpider
from liaoning.rules import *
from zc_core.util.batch_gen import time_to_batch_no


class SkuSpider(BaseSpider):
    name = 'sku'
    # 常用链接
    index_url = 'http://218.60.151.1:8081/gp-webapp-mall/'
    sku_list_url = 'http://218.60.151.1:8081/gp-webapp-mall/product/search?page={}&display=1&preOptionString=01_*_01_{}&preSortString='

    def __init__(self, batchNo=None, *args, **kwargs):
        super(SkuSpider, self).__init__(batchNo=batchNo, *args, **kwargs)

    def start_requests(self):
        # self.cookies = SeleniumLogin().get_cookies()
        self.cookies = {'JSESSIONID': '246E4AEF5E7C7686943EC3D9554A06C6'}
        if not self.cookies:
            self.logger.error('init cookie failed...')
            return
        self.logger.info('init cookie: %s', self.cookies)

        # 首页分类
        yield Request(
            url=self.index_url,
            meta={
                'reqType': 'catalog',
                'batchNo': self.batch_no,
            },
            headers={
                'Host': '218.60.151.1:8081',
                'Connection': 'keep-alive',
                'Cache-Control': 'max-age=0',
                'Upgrade-Insecure-Requests': '1',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                'Accept-Encoding': 'gzip, deflate',
                'Accept-Language': 'zh-CN,zh;q=0.9',
            },
            cookies=self.cookies,
            callback=self.parse_catalog,
            errback=self.error_back,
        )

    # 处理首页品类列表
    def parse_catalog(self, response):
        cats = parse_catalog(response)
        if cats:
            self.logger.info('品类: count[%s]' % len(cats))
            yield Box('catalog', self.batch_no, cats)

            for cat in cats:
                # 请求sku
                level = cat.get('level')
                if level == 3:
                    page = 1
                    yield Request(
                        url=self.sku_list_url.format(page, cat.get('catalogId')),
                        meta={
                            'reqType': 'sku',
                            'batchNo': self.batch_no,
                            'page': page,
                            'catalog3Id': cat.get('catalogId'),
                        },
                        headers={
                            'Host': '218.60.151.1:8081',
                            'Connection': 'keep-alive',
                            'Cache-Control': 'max-age=0',
                            'Upgrade-Insecure-Requests': '1',
                            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400',
                            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                            'Accept-Encoding': 'gzip, deflate',
                            'Accept-Language': 'zh-CN,zh;q=0.9',
                        },
                        cookies=self.cookies,
                        callback=self.parse_sku_pages,
                        errback=self.error_back,
                    )

    # 分页列表
    def parse_sku_pages(self, response):
        meta = response.meta
        catalog3_id = meta.get('catalog3Id')
        total_page = parse_sku_pages(response)
        if total_page:
            self.logger.info('页数: cat=%s, count=%s' % (catalog3_id, total_page))
            for page in range(1, total_page + 1):
                yield Request(
                    url=self.sku_list_url.format(page, catalog3_id),
                    meta={
                        'reqType': 'sku',
                        'batchNo': self.batch_no,
                        'page': page,
                        'catalog3Id': catalog3_id,
                    },
                    headers={
                        'Host': '218.60.151.1:8081',
                        'Connection': 'keep-alive',
                        'Cache-Control': 'max-age=0',
                        'Upgrade-Insecure-Requests': '1',
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400',
                        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                        'Accept-Encoding': 'gzip, deflate',
                        'Accept-Language': 'zh-CN,zh;q=0.9',
                    },
                    cookies=self.cookies,
                    callback=self.parse_sku,
                    errback=self.error_back,
                )
        else:
            self.logger.info('分类无商品: cat=%s' % catalog3_id)

    # 处理sku列表
    def parse_sku(self, response):
        meta = response.meta
        cur_page = meta.get('page')
        catalog3_id = meta.get('catalog3Id')

        sku_list = parse_sku(response)
        if sku_list:
            self.logger.info('清单: cat=%s, page=%s, cnt=%s' % (catalog3_id, cur_page, len(sku_list)))
            yield Box('sku', self.batch_no, sku_list)
        else:
            self.logger.info('空页: cat=%s, page=%s' % (catalog3_id, cur_page))
